<template>
  <div class="concent"   v-loading="loading">
    <div style="background-color: #fff; padding: 1vw; box-sizing: border-box;">
      <el-form  :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item :label="$t('Order_module.Waybill_number')">
          <!-- 运单号 -->
          <el-input v-model="formInline.logisticsNo" :placeholder="$t('Order_module.Waybill_number')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('Order_module.Batch_number')">
          <!-- 批次号 -->
          <el-input v-model="formInline.manifestNo" :placeholder="$t('Order_module.Batch_number')"></el-input>
        </el-form-item>
        <!-- 是否推送 -->
        <el-form-item :label="$t('public.Push_status')">
          <!-- 批次号 -->
          <el-select v-model="formInline.pushStatus" :placeholder="$t('public.Please_select')">
              <el-option v-for="ite in ISpush" :key="ite.val" :label="ite.label" :value="ite.val">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="searchLoading" @click="search">{{$t('public.query')}}</el-button>
          <el-button type="primary" :loading="resetLoading" @click="resetting" >{{$t('public.resetting')}}</el-button>
          <el-button type="primary" :loading="Track_templateLoading" @click="Track_template" >{{$t('public.Track_template')}}</el-button>
          <!-- -->
          <el-button type="primary" :disabled="checkedCities.length<=0"  @click="piLiang" :loading="Track_templateLoading"  >批量编辑</el-button>
        </el-form-item>

        <el-form-item label="">
          <!-- 批次号 -->
          <el-upload style="margin-left: 10px; margin-right: 10px;" ref="upload" action="https://jsonplaceholder.typicode.com/posts/"
            :http-request="upload_file"
            :show-file-list = "false"
            :file-list="fileList"
            :before-upload="before_upload"
            >
            <el-button :loading="upload_file_loading" slot="trigger"  type="primary" >{{$t('public.bulk_import')}}</el-button>
          </el-upload>
        </el-form-item>
      </el-form>

      <el-checkbox-group v-model="checkedCities" @change="handleSelectionChange">

      <el-table :data="tableData" border style="width: 100%"  @selection-change="">
        <!-- 多選 -->
        <el-table-column  align="center" width="80" fixed="left">
          <template slot-scope="{row}">
            <el-checkbox :disabled="row.pushStatus" :label="row.id" >{{null}}</el-checkbox>
          </template>
           <template slot="header" slot-scope="{row}">
              <el-button :loading="upload_file_loading" slot="trigger" @click="quan_choose" type="text" >{{isAll?'全不选':'全选'}}</el-button>
           </template>
        </el-table-column>
        <!-- 批次编号 -->
        <el-table-column prop="manifestNo" :label="$t('Order_module.Batch_number')"  align="center" min-width="120"> </el-table-column>
        <!-- 物流公司运单号 -->
        <el-table-column prop="orderId" :label="$t('Order_module.Waybill_number')"  align="center" min-width="120"> </el-table-column>
        <!-- 推送状态 -->
        <el-table-column prop="pushStatus" :label="$t('public.Push_status')"  align="center" min-width="120">
          <template slot-scope="{row}">
           {{row.pushStatus?row.pushStatus==true?$t('public.Pushed'):$t('public.Not_pushed'):'-'}}
          </template>
        </el-table-column>
        <!-- 事件操作code -->
        <el-table-column prop="scanType" :label="$t('public.scanType')"  align="center" min-width="120">
          <template slot-scope="{row}">
           {{row.scanType?row.scanType:'-'}}
          </template>
        </el-table-column>
        <!-- 事件操作name -->
        <el-table-column prop="scanName" :label="$t('public.scanName')"  align="center" min-width="120">
          <template slot-scope="{row}">
           <!-- {{row.scanName?row.scanName:'-'}} -->
           <span v-if="row.scanId==1">{{$t('public.Overseas_warehouse_collection')}}</span>
           <span v-if="row.scanId==2">{{$t('public.international_transport')}}</span>
           <span v-if="row.scanId==3">{{$t('public.Start_cross_border_transport')}}</span>
           <span v-if="row.scanId==4">{{$t('public.End_of_cross_border_traffic')}}</span>
           <span v-if="row.scanId==5">{{$t('public.customs_clearance_of_import')}}</span>
           <span v-if="row.scanId==6">{{$t('public.customs_clearance')}}</span>

          </template>
        </el-table-column>
        <!-- 跟踪信息描述 -->
        <el-table-column prop="des"  :label="$t('public.Trace_information_description')"  align="center" min-width="120">
          <template slot-scope="{row}">
           {{row.des?row.des:'-'}}
          </template>
        </el-table-column>
        <!-- 操作时间 -->
        <el-table-column prop="operateTime" :label="$t('public.operateTime')"  align="center" min-width="120"> </el-table-column>
        <!-- 操作 -->
        <el-table-column fixed="right" align="center"  :label="$t('public.operate')" width="100">
          <template slot-scope="scope">
            <!-- <el-button @click="handleClick(scope.row)" type="text" size="small">{{$t('public.examine')}}</el-button> -->
            <el-button type="text"  @click="seeinfo(scope.row)" size="small">{{$t('public.edit')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      </el-checkbox-group>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 50, 200, 400]"
        :page-size="limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
        <!-- 编辑对话框 -->
        <el-dialog
          :title="title"
          :visible.sync="dialogVisible"
          width="60%"
          :close-on-click-modal="false"
          :before-close="handleClose">
          <el-form v-if="dialogVisible" :rules="rules" ref="ruleForm"  :inline="true"  :model="dataInfo" >
            <el-form-item style="width: 30%;" :label="$t('Order_module.Batch_number')">
              <el-input  disabled v-model="dataInfo.list[0].manifestNo"></el-input>
            </el-form-item>
            <el-form-item style="width: 35%;" :label="$t('Order_module.Waybill_number')">
              <el-input  disabled v-model="dataInfo.list[0].orderId"></el-input>
            </el-form-item>
            <!-- <el-form-item  prop="ok"  label=" " style="width: 270px;" >
              <el-select v-model="optionsVal" :placeholder="$t('public.Please_select')">
                  <el-option v-for="ite in options" :key="ite.val" :label="ite.label" :value="ite.val">
                  </el-option>
                </el-select>
            </el-form-item> -->
            <div v-for="(item,index) in dataInfo.list"  :key="index" style="border: 1px solid #ccc ; margin-bottom: 10px ; padding: 5px; box-sizing: border-box; border-radius: 10px;">
              <el-form-item  style="width: 120px;" >
                <el-input disabled v-if="item.scanId==1" :value="$t('public.Overseas_warehouse_collection')">
                </el-input>
                <el-input disabled v-if="item.scanId==2" :value="$t('public.international_transport')">
                </el-input>
                <el-input disabled v-if="item.scanId==3" :value="$t('public.Start_cross_border_transport')">
                </el-input>
                <el-input disabled  v-if="item.scanId==4" :value="$t('public.End_of_cross_border_traffic')">
                </el-input>
                <el-input disabled v-if="item.scanId==5" :value="$t('public.customs_clearance_of_import')">
                </el-input>
                <el-input disabled v-if="item.scanId==6" :value="$t('public.customs_clearance')">
                </el-input>
              </el-form-item>
              <el-form-item style="width:width:240px;" >
                <el-input disabled maxlength="200" style="width:240px;" :placeholder="$t('public.Trace_information_description')"   :value="item.des?item.des:'-'"></el-input>
              </el-form-item>
              <el-form-item style="width: 100px;">
                <el-input  :placeholder="$t('Order_module.city')" maxlength="20"  type="text"  v-model="item.city"></el-input>
              </el-form-item>

              <el-form-item >
                 <el-date-picker
                      v-model="item.operateTime"
                      type="datetime"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      format="yyyy-MM-dd HH:mm:ss"
                      :placeholder="$t('public.Timing')">
                    </el-date-picker>
              </el-form-item>
              <div>
                <el-form-item v-if="item.scanId==3" prop="ok"  label=" " style="width: 250px;" >
                  <el-select v-model="optionsVal" :placeholder="$t('public.Please_select')">
                      <el-option
                        v-for="ite in options"
                        :key="ite.val"
                        :label="ite.label"
                        :value="ite.val">
                      </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item style="width: 150px;" v-if="item.scanId==3" >
                  <el-input  :placeholder="optionsVal==2?$t('public.flight_number'):$t('public.hull_number')" maxlength="20" type="text"  v-model="item.transportNumber"></el-input>
                </el-form-item>
              </div>
            </div>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">{{$t('public.cancellation')}}</el-button>
            <el-button  type="primary" :loading="submitLoading" @click="submit()">{{$t('public.determine')}}</el-button>
          </span>
        </el-dialog>
        <!-- 批量编辑对话框 -->
        <el-dialog
          title="批量编辑"
          :visible.sync="pi_show"
          width="60%"
          :close-on-click-modal="false"
          :before-close="PIClose">
          <el-form v-if="PIClose" :rules="rules" ref="piForm"  :inline="true"  :model="dataInfo" >

            <div v-for="(item,index) in dataInfo.list"  :key="index" style="border: 1px solid #ccc ; margin-bottom: 10px ; padding: 5px; box-sizing: border-box; border-radius: 10px;">
              <el-form-item  style="width: 120px;" >
                <el-input disabled v-if="item.scanId==1" :value="$t('public.Overseas_warehouse_collection')">
                </el-input>
                <el-input disabled v-if="item.scanId==2" :value="$t('public.international_transport')">
                </el-input>
                <el-input disabled v-if="item.scanId==3" :value="$t('public.Start_cross_border_transport')">
                </el-input>
                <el-input disabled  v-if="item.scanId==4" :value="$t('public.End_of_cross_border_traffic')">
                </el-input>
                <el-input disabled v-if="item.scanId==5" :value="$t('public.customs_clearance_of_import')">
                </el-input>
                <el-input disabled v-if="item.scanId==6" :value="$t('public.customs_clearance')">
                </el-input>
              </el-form-item>
              <el-form-item style="width:width:240px;" >
                <el-input disabled maxlength="200" style="width:240px;" :placeholder="$t('public.Trace_information_description')"   :value="item.des?item.des:'-'"></el-input>
              </el-form-item>
              <el-form-item style="width: 100px;">
                <el-input  :placeholder="$t('Order_module.city')" maxlength="20"  type="text"  v-model="item.city"></el-input>
              </el-form-item>

              <el-form-item >
                 <el-date-picker
                      v-model="item.operateTime"
                      type="datetime"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      format="yyyy-MM-dd HH:mm:ss"
                      :placeholder="$t('public.Timing')">
                    </el-date-picker>
              </el-form-item>
              <div>
                <el-form-item v-if="item.scanId==3" prop="ok"  label=" " style="width: 250px;" >
                  <el-select v-model="optionsVal" :placeholder="$t('public.Please_select')">
                      <el-option
                        v-for="ite in options"
                        :key="ite.val"
                        :label="ite.label"
                        :value="ite.val">
                      </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item style="width: 150px;" v-if="item.scanId==3" >
                  <el-input  :placeholder="optionsVal==2?$t('public.flight_number'):$t('public.hull_number')" maxlength="20" type="text"  v-model="item.transportNumber"></el-input>
                </el-form-item>
              </div>
            </div>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="pi_show = false">{{$t('public.cancellation')}}</el-button>
            <el-button  type="primary" :loading="piLoading" @click="pi_submit()">{{$t('public.determine')}}</el-button>
          </span>
        </el-dialog>
  </div>
</template>
<script>
  import {
    trace_list,
    trace_info,
    trace_update,
    trace_batchInfo,
    trace_batchUpdate
  } from '@/api/wqzApi'
  import store from '@/store'
  import axios from 'axios'
  import { getToken } from '@/utils/auth'
  const cityOptions = [];
  export default {
    components: {

    },
    data() {
      return {

        piLoading:false, //批量编辑loading
        pi_show:false, // 批量编辑对话框
        isAll: false, //是否全选
        all_select:[],//可以全选的选项
        isIndeterminate: false , //半选
        checkedCities:[] , //多选选中
        searchLoading:false,
        resetLoading:false,
        upload_file_loading:false,
        Track_templateLoading:false,
        rules:{
          // 提交表单验证
          list:[
            {required: true, validator: (rule, value, callback)=>{
              console.log(this.optionsVal , '-----')
              if (this.optionsVal!='') {
                callback()
               } else {
                 callback(new Error(this.$t('public.Enter')));
               }

            }, trigger: ['change' , 'blur'] },
          ],
          ok: [
            {required: true, validator: (rule, value, callback)=>{
              console.log(this.optionsVal)
              if (this.optionsVal!='' || this.optionsVal!=null) {
                callback()
               } else {
                 callback(new Error(this.$t('public.Enter')));
               }

            }, trigger: ['change' , 'blure'] },

          ],
        },
        fileList:[],//文件上传列表
        submitLoading:false,
        loading:false,
        title:'', //对话框标题
        optionsVal:'1',
        options:[
          // 站点类型

          {label: this.$t('public.aviation') , val:'2'},
          {label:this.$t('public.sea_transportation')  , val:'1'},
        ],
        ISpush:[
          // 站点类型
          {label: this.$t('public.Pushed') , val:1},
          {label:this.$t('public.Not_pushed')  , val:0},
        ],
        dialogVisible:false, //对话框
        formInline:{ //搜索内容
          manifestNo:'',
          logisticsNo:'',
          pushStatus:null,
        },
        dataInfo:{
          ok:[],
          list:[
            {manifestNo:''}
          ]
        },//详情信息
        page:1,
        limit:10,
        total:0,
        tableData:[], //列表
      }
    },

    created() {

    },
    mounted() {
      this.getList()
    },
    destroyed() {

    },

    methods: {
      PIClose(){
        this.pi_show = !this.pi_show
      },
      pi_submit(){

       this.piLoading = true
        this.$refs.piForm.validate((valid) => {
         if (valid) {
           for(var i=0 ;i<this.dataInfo.list.length ; i++){
             if(this.dataInfo.list[i].city=='' || this.dataInfo.list[i].city==null ){
               this.piLoading= false
               this.$message({
                 type:'warning',
                 message:this.$t('public.Please_complete_the_steps')+(i+1)
               })
               return
             }
             // if(this.dataInfo.list[i].operateTime=='' || this.dataInfo.list[i].operateTime==null ){
             //   this.piLoading= false
             //   this.$message({
             //     type:'warning',
             //     message:this.$t('public.Please_complete_the_steps')+(i+1)
             //   })
             //   return
             // }

             if(this.dataInfo.list[i].scanId==3 ){
               if(this.dataInfo.list[i].transportNumber=='' || this.dataInfo.list[i].transportNumber==null){
                 this.piLoading= false
                 this.$message({
                   type:'warning',
                   message:this.$t('public.Please_complete_the_steps')+(i+1)
                 })
                 return
               }
             }
           }
           this.dataInfo.list.forEach((item,index)=>{
             this.dataInfo.list[index].transportationType = this.optionsVal
             if(item.scanId==1){
               this.dataInfo.list[index].des = `包裹已揽收，准备发往${item.city}${this.optionsVal==1?'码头':'国际机场'}`
             }
             if(item.scanId==2){
               this.dataInfo.list[index].des = `包裹已到达${item.city}${this.optionsVal==1?'码头':'国际机场'}，运力配载中`
             }
             if(item.scanId==3){
               this.dataInfo.list[index].des = `包裹已启航，${this.optionsVal==1?'船号':'航班号'}${item.transportNumber}`
             }
             if(item.scanId==4){
               this.dataInfo.list[index].des = `包裹已到达${item.city}${this.optionsVal==1?'码头':'国际机场'}`
             }
             if(item.scanId==5){
               this.dataInfo.list[index].des = `包裹清关中`
             }
             if(item.scanId==6){
               this.dataInfo.list[index].des = `包裹已清关，待京东物流揽收`
             }
           })

            var data = {
              ids: JSON.stringify(this.checkedCities) ,
              dataList:JSON.stringify(this.dataInfo.list) ,
            }
           trace_batchUpdate(data).then(res=>{
                this.piLoading = false
                this.pi_show = false
                  this.$refs.piForm.resetFields()
                  this.checkedCities = []
                  this.getList()
           }).catch(err=>{
                  this.piLoading = false
           })
         } else {
           console.log('error submit!!');
           this.piLoading = false

           return false;
         }
       });

        console.log(this.dataInfo.list)
      },
      piLiang(){
       trace_batchInfo({}).then(res=>{
         res.traceList.forEach((item,index)=>{
           res.traceList[index].scanId = index+1
         })
         var dataInfo = {
           list:res.traceList
         }
         this.dataInfo = dataInfo
         this.optionsVal = '1'
         this.pi_show = true
       })
      },
      quan_choose(){
        this.checkedCities = this.isAll ? []  : this.all_select;
        this.isAll = !this.isAll
      },
      handleSelectionChange(value){
        this.checkedCities = value
        var length = value.length
        var all_length = this.all_select.lenght
        if(length == all_length){
          this.isAll = true
        }else{
          this.isAll = false
        }
      },
      Track_template(){
        this.Track_templateLoading = true
        this.$export_down2('api/templatesDown/trace' , [] ,  this.$t('public.Track_template')).then(err=>{
          this.Track_templateLoading = false
        })
      },
      upload_file(e){
        var files = e.file
        console.log(files , '选择的文件')
        // 创建FormData
        this.upload_file_loading = true
        var formData = new FormData()
        formData.append('ordersFile', files)
        var url = process.env.VUE_APP_BASE_API + '/api/trace/batch'
        var  token = getToken()
        // 设置请求头信息
        const headers = {
          'Content-Type': 'multipart/form-data',
          'Token' : token,
          'Lang' : this.$store.getters.language=="zh"?'zh_CN':'ko_KR'
        }
        axios.post(url, formData, {
          headers
        }).then(res => {
          if(res.data.code == 0){
            this.$message({
              type:'success',
              message:this.$t('public.Operation_successful')
            })
            this.upload_file_loading = false
            this.getList()
          }else{
            this.upload_file_loading = false
            this.$message({
              type:'error',
              message:res.data.msg,
              dangerouslyUseHTMLString:true
            })
          }

        })
      },
      before_upload(file){
       if(file.type == 'application/vnd.ms-excel' || file.type=='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'){
         this.upFile = file
       }else{
         this.$message({
           message:this.$t('public.Only_xls_files_can_be_uploaded'),
           type:'error'
         })
         return false
       }
      },
      submit(){
        this.submitLoading = true
         this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            for(var i=0 ;i<this.dataInfo.list.length ; i++){
              if(this.dataInfo.list[i].city=='' || this.dataInfo.list[i].city==null ){
                this.submitLoading = false
                this.$message({
                  type:'warning',
                  message:this.$t('public.Please_complete_the_steps')+(i+1)
                })
                return
              }
              // if(this.dataInfo.list[i].operateTime=='' || this.dataInfo.list[i].operateTime==null ){
              //   this.submitLoading = false
              //   this.$message({
              //     type:'warning',
              //     message:this.$t('public.Please_complete_the_steps')+(i+1)
              //   })
              //   return
              // }

              if(this.dataInfo.list[i].scanId==3 ){
                if(this.dataInfo.list[i].transportNumber=='' || this.dataInfo.list[i].transportNumber==null){
                  this.submitLoading = false
                  this.$message({
                    type:'warning',
                    message:this.$t('public.Please_complete_the_steps')+(i+1)
                  })
                  return
                }
              }
            }
            this.dataInfo.list.forEach((item,index)=>{
              this.dataInfo.list[index].transportationType = this.optionsVal
              if(item.scanId==1){
                this.dataInfo.list[index].des = `包裹已揽收，准备发往${item.city}${this.optionsVal==1?'码头':'国际机场'}`
              }
              if(item.scanId==2){
                this.dataInfo.list[index].des = `包裹已到达${item.city}${this.optionsVal==1?'码头':'国际机场'}，运力配载中`
              }
              if(item.scanId==3){
                this.dataInfo.list[index].des = `包裹已启航，${this.optionsVal==1?'船号':'航班号'}${item.transportNumber}`
              }
              if(item.scanId==4){
                this.dataInfo.list[index].des = `包裹已到达${item.city}${this.optionsVal==1?'码头':'国际机场'}`
              }
              if(item.scanId==5){
                this.dataInfo.list[index].des = `包裹清关中`
              }
              if(item.scanId==6){
                this.dataInfo.list[index].des = `包裹已清关，待京东物流揽收`
              }
            })
            console.log(this.dataInfo)
            trace_update(this.dataInfo.list).then(res=>{
              this.submitLoading = false
              this.dialogVisible = false
              this.$refs.ruleForm.resetFields()
              this.getList()
            }).catch(err=>{
              this.submitLoading = false
            })
          } else {
            console.log('error submit!!');
            this.submitLoading = false

            return false;
          }
        });


      },
      selectChagne(e){
        // 站点类型选择


        this.dataInfo.siteType = String(e)
      },
      seeinfo(row){
        // 查看详情
        console.log(row)
        this.title = this.$t('public.edit')
        var data = {
          logisticsNo:row.orderId
        }
        this.loading = true
        trace_info(data).then(res=>{
          this.dataInfo ={list:res.traceList , ok:[]}

          this.dialogVisible = true
          this.optionsVal = String(res.traceList[0].transportationType==null?'':res.traceList[0].transportationType)
          this.loading = false
        }).catch(err=>{
          this.loading = false
        })
      },
      handleClose(){
        // 关闭对话框
        this.dialogVisible = !this.dialogVisible
      },
      handleSizeChange(e){
        this.limit = e
        this.getList()
      },
      handleCurrentChange(e){
        this.page= e
        this.getList()
      },
      getList(){
        var data = {
          page:this.page,
          limit:this.limit,
          ...this.formInline
        }
        this.all_select = []
        this.isAll = false
        this.checkedCities=[] 
          // isAll: false, //是否全选
          // all_select:[],//可以全选的选项
          // isIndeterminate: false , //半选
          // checkedCities:[] , //多选选中
        trace_list(data).then(res=>{
          console.log(res.page.list)
          // cityOptions
          res.page.list.forEach((item,index)=>{
            if(!item.pushStatus){
              this.all_select.push(item.id)
            }
          })
          console.log(this.all_select , '可以全选的')
          this.total = res.page.totalCount
          this.tableData = res.page.list
          this.searchLoading = false
          this.resetLoading = false
        }).catch(err=>{
          this.searchLoading = false
          this.resetLoading = false
        })
      },
      search(){
        this.searchLoading = true
        this.page = 1
        this.getList()
      },
      resetting(){
        this.resetLoading = true
        this.formInline = {
          manifestNo:'',          logisticsNo:''
        }
        this.getList()
      }
    }
  }
</script>

<style lang="scss" scoped>
  .concent{
    padding: 1vw;
    box-sizing: border-box;
    width: 100%;
    // flex: 1;
    display: flex;
    flex-direction: column;
  }
</style>
